<?php

namespace app\admin\model;

use think\facade\Cache;
use app\common\model\BaseModel;
use think\helper\Str;

class AuthRule extends BaseModel
{
    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    const MENU_KEY_STR = '__menu__str__';
    const MENU_KEY_ARRAY = '__menu__array__';

    protected static function onAfterWrite($model)
    {
        Cache::delete(config('app.cache_prefix').'__menu__');
    }

    public function getTitleAttr($value, $data)
    {
        return __($value);
    }
    public static function getAllMenuStr($refresh=false)
    {
        $cache = Cache::get(self::MENU_KEY_STR);
        if(empty($cache)||$refresh){
            $allMenu = self::getAllMenuArray($refresh);
            $allMenu = tree_to_menu($allMenu);
            Cache::set(self::MENU_KEY_STR, $allMenu);
            $cache = $allMenu;
        }
        return $cache;
    }
    public static function getAllMenuArray($refresh=false)
    {
        $cache = Cache::get(self::MENU_KEY_ARRAY);
        if(empty($cache)||$refresh){
            $where = [
                ['status','=','1'],
                ['ismenu','=','1']
            ];
            $allMenu = self::where($where)->order('weigh', 'desc')->order('id', 'asc')->select()->toArray();
            foreach ($allMenu as $k=>$v){
                $v['module'] = app_map_get($v['module'],false);
                $v['title'] = __($v['title']);
                $allMenu[$k] = $v;
            }
            $allMenu = list_to_tree($allMenu, 'id', 'pid', 'children', 0);
            Cache::set(self::MENU_KEY_ARRAY, $allMenu);
            $cache = $allMenu;
        }
        return $cache;
    }
    public function children()
    {
        return $this->hasMany(self::class, 'pid', 'id');
    }
//    public function setNameAttr($value, $data)
//    {
//        if (empty($data['route'])) {
//            $this->set('route', tp5ControllerToTp6Controller($data['name'],$data['ismenu']));
//        }
//        $this->set('name', $value);
//    }
}
